package services

import (
	"errors"
	"fmt"
	"hft/Database/admin"
	utils "hft/Http/Utils"
	"hft/global"
	"hft/tools"
	"regexp"

	"gorm.io/gorm"
)

type BackEnter struct{}

func (b *BackEnter) EnterChildAccount(username string, claims *tools.BaseClaims) (token string, err error) {

	var parseAccount *utils.ParseAccount

	var account *admin.Account

	var childAccount *admin.Account

	global.OC_DB.Transaction(func(tx *gorm.DB) error {

		err = tx.Scopes(parseAccount.Parse(*claims, tx)).First(&account).Error

		if err != nil {
			return errors.New("无该账号信息")
		}

		err = tx.Where("username = ?", username).First(&childAccount).Error

		if err != nil {
			return errors.New("找不到要进入的子账号信息")
		}

		// 确定账号是否可以进入
		matchString := fmt.Sprintf("^%v", account.Link)

		match, err := regexp.MatchString(matchString, childAccount.Link)

		if err != nil {
			return errors.New("无效的匹配")
		}

		if !match {
			return errors.New("角色不匹配")
		}

		// 同时生成用户的token
		var j = tools.NewJWT()

		customClaims := j.CreateClaims(tools.BaseClaims{Username: childAccount.Username}, "3h", "1h")

		tokenString, err := j.CreateToken(customClaims)

		if err != nil {
			return errors.New("子账号进入失败")
		}

		token = tokenString

		return nil
	})

	return token, nil
}

var BackEnterService = new(BackEnter)
